<!-- 文章模块 -->
<template>
  <div class="article-container" >
    <van-nav-bar
      title="文章详细"
      left-arrow
      @click-left="$router.back()"
      fixed
      placeholder
    />

    <van-cell-group inset>
      <van-cell>
        <div slot="title" class="title">{{ articleInfo.title }}</div>
      </van-cell>
      <van-cell center class="user-info">
        <div slot="title" class="name">{{ articleInfo.aut_name }}</div>
        <van-image
          class="avatar"
          slot="icon"
          round
          width="35"
          height="35"
          :src="articleInfo.aut_photo"
        />
        <van-button
          slot="right-icon"
          round
          :type="articleInfo.is_followed ? 'default' : 'info'"
          class="btn"
          :icon="articleInfo.is_followed ? '' : 'plus'"
          @click="onFollow"
          :loading="isFollowLoading"
          >{{ articleInfo.is_followed ? "已关注" : "关注" }}</van-button
        >
        <span slot="label" class="pubDate">
          {{ articleInfo.pubdate | relativeTime }}</span
        >
      </van-cell>

      <div class="markdown-body" ref="article-content">
        <div v-html="articleInfo.content"></div>
      </div>

      <CommentList
        :list="list"
        :source="articleId"
        :type="'a'"
        @total_count="total_count = $event"
        @reply-click="onReplyClick"
      />
    </van-cell-group>

    <div class="footer">
      <van-button type="default" @click="showComment = !showComment"
        >写评论</van-button
      >
      <div class="icons">
        <van-icon name="comment-o" :badge="total_count" />
        <van-icon
          :style="{ color: articleInfo.is_collected ? 'orange' : '' }"
          :name="articleInfo.is_collected ? 'star' : 'star-o'"
          @click="onCollect"
        />
        <van-icon
          :style="{ color: articleInfo.attitude === 1 ? 'hotPink' : '' }"
          :name="articleInfo.attitude === 1 ? 'good-job' : 'good-job-o'"
          @click="onLike"
        />
        <van-icon name="share-o" />
      </div>
    </div>

    <!-- 发布评论 -->
    <van-popup v-model="showComment" position="bottom">
      <PublishComment
        :traget="articleId"
        :articleId="articleId"
        @post-success="successComment"
      />
    </van-popup>

    <!-- 回复评论 -->
    <van-popup v-model="showReply" position="bottom" :style="{ height: '70%' }">
      <comment-reply
        :comment="comment"
        :articleId="articleId"
        @close="showReply = false"
        v-if="showReply"
      />
    </van-popup>
  </div>
</template>

<script>
import "../../styles/githubMarkDown.less";
import { ImagePreview } from "vant";
import {
  getArticleById,
  addCollect,
  deleteCollect,
  addLike,
  deleteLike,
} from "../../api/article";
import { addFollow, deleteFollow, getUserInfo } from "../../api/user";
import { mapState } from "vuex";
import CommentList from "./components/comment-list.vue";
import PublishComment from "./components/publishComment.vue";
import CommentReply from "./components/comment-reply.vue";

export default {
  name: "articles",
  props: ["articleId"],
  data() {
    return {
      articleInfo: {},
      isFollowLoading: false,
      isCollectLoading: false,
      showComment: false,
      list: [],
      total_count: 0, //评论量
      showReply: false,
      comment: {},
    };
  },
  computed: {
    ...mapState(["userInfo"]),
  },
  methods: {
    async loadArticle() {
      try {
        let { data } = await getArticleById(this.articleId);
        this.articleInfo = data.data;
        /**
         * 此处不能直接获取到dom !
         *  因为数据改变影响视图更新(dom数据)不是立即更新的
         *  所以如果需要在修改数据之后马上操作被改数据影响的dom,需要把这个代码放入 this.$nextTick中
         * 
         *错误: 获取文章的DOM容器
            const articleContent = this.$refs["article-content"];
            let imgs = articleContent.querySelectorAll("img");
            console.log(imgs);
         */
        this.$nextTick(() => {
          this.handleImagePreview();
        });
      } catch (error) {}
    },

    handleImagePreview() {
      const articleContent = this.$refs["article-content"];
      let imgs = articleContent.querySelectorAll("img");
      let imgUrl = [];
      imgs.forEach((img, index) => {
        imgUrl.push(img.src);
        img.onclick = () => {
          ImagePreview({
            images: imgUrl,
            startPosition: index,
          });
        };
      });
    },

    async onFollow() {
      try {
        this.isFollowLoading = true;
        if (this.articleInfo.is_followed) {
          // 取消关注操作
          let data = await deleteFollow(this.articleInfo.aut_id);
        } else {
          if (this.userInfo === null) {
            this.isFollowLoading = false;
            return this.$toast.fail("请先登录!");
          }
          const { data } = await getUserInfo();
          const id = this.articleInfo.aut_id;
          if (data.data.id === id) {
            this.isFollowLoading = false;
            return this.$toast.fail("不能关注自己");
          }
          let ret = await addFollow(id);
          if (ret.data.status === 201) {
            this.$toast.success("关注用户成功");
          }
        }
        this.articleInfo.aut_id = !this.articleInfo.aut_id;
        this.isFollowLoading = false;
      } catch (error) {
        console.log(error);
      }
    },

    async onCollect() {
      this.$toast.loading({
        message: "请求中",
        forbidClick: true,
      });
      try {
        if (this.articleInfo.is_collected) {
          // 取消收藏
          const { data } = await deleteCollect(this.articleId);
        } else {
          const { data } = await addCollect(this.articleId);
        }

        this.articleInfo.is_collected = !this.articleInfo.is_collected;
        this.$toast.success(
          this.articleInfo.is_collected ? "收藏成功" : "取消收藏成功"
        );
      } catch (error) {
        return console.log(error);
      }
    },

    async onLike() {
      this.$toast.loading({
        message: "请求中",
        forbidClick: true,
      });
      if (this.articleInfo.attitude === 1) {
        await deleteLike(this.articleId);
        this.articleInfo.attitude = -1;
      } else {
        await addLike(this.articleId);
        this.articleInfo.attitude = 1;
      }
      this.$toast.success(
        `${this.articleInfo.attitude === 1 ? "" : "取消"}点赞成功`
      );
    },

    successComment(comment) {
      this.list.unshift(comment);
      this.total_count++;
      this.showComment = false;
    },
    onReplyClick(comment) {
      this.comment = comment;
      this.showReply = true;
    },
  },
  created() {
    this.loadArticle();
  },
  components: {
    CommentList,
    PublishComment,
    CommentReply,
  },

};
</script>


<style lang="less" scoped>
.article-container {
  width: 100%;
  overflow: hidden;
  box-sizing: border-box;
  .title {
    font-size: 20px;
    color: #3a3a3a;
    padding: 14px;
    margin: 0;
  }
  .van-cell-group {
    height: calc(100vh - 51px - 45px);
    overflow: auto;
    box-sizing: border-box;
    padding: 5px;
  }
  /deep/.van-cell-group--inset {
    box-sizing: border-box;
    margin: 5px;
  }
  .user-info {
    .name {
      margin-bottom: -3px;
      padding-bottom: 0;
      font-size: 12px;
      color: #333333;
    }
    .avatar {
      width: 35px;
      height: 35px;
      margin-right: 8px;
    }
    .pubDate {
      font-size: 11px;
      color: #b4b4b4;
    }
    .btn {
      width: 85px;
      height: 29px;
    }
  }

  /deep/.markdown-body {
    font-size: 14px;
  }

  .footer {
    height: 44px;
    line-height: 45px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: fixed;
    background-color: white;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 0 15px;
    border-top: 1px solid #cccccc;
    .van-button {
      width: 40%;
      height: 25px;
      border-radius: 10px;
      font-size: 13px;
      color: #9a9797;
    }
    .icons {
      width: 45%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .van-icon {
        font-size: 23px;
      }
    }
  }
}
</style>